<?php
/**
 * @author 	Vu Nhat Lam
 * 			Mail: lamvnd@gmail.com
 * 			Mobile: 0984 52 62 68
 * @version 1.0.0
 */
// ######################## SET PHP ENVIRONMENT ###########################
error_reporting(E_ALL & ~E_NOTICE); 
if (!is_object($vbulletin->db))
{
	exit;
}

// ##################### DEFINE IMPORTANT CONSTANTS #######################
define('DATECUT', TIMENOW - $vbulletin->options['torrent_interval'] - 60);

// ########################################################################
// ######################### START MAIN SCRIPT ############################
// ########################################################################
// Delete peers not updated
$peers = $vbulletin->db->query_read_slave("
	SELECT peer_id, torrentid, `left`
	FROM " . TABLE_PREFIX . "torrentpeers
	WHERE updated < " . DATECUT . "
");
while ($peer = $vbulletin->db->fetch_array($peers))
{
	$vbulletin->db->query_write("
		DELETE FROM " . TABLE_PREFIX . "torrentpeers
		WHERE " . hash_where('peer_id', $peer['peer_id']) . "
			AND updated < " . DATECUT . "
	");

	if ($peer['left'])
	{
		$update = "leechers = IF(leechers > 0, leechers - 1, 0)";
	}
	else
	{
		$update = "seeders = IF(seeders > 0, seeders - 1, 0)";
	}

	$vbulletin->db->query_write("
		UPDATE " . TABLE_PREFIX . "torrent SET $update
		WHERE torrentid = {$peer['torrentid']}
	");
}
$vbulletin->db->free_result($peers);

log_cron_action('Bittorrent Tracker cleanup', $nextitem);
